package com.tzq.bearstory;

import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import android.widget.RemoteViews;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;

import java.util.List;

import static com.tzq.bearstory.MyPlayerReceiver.*;

public class MyService extends Service {
    public static final int NOTIFICATION_ID = 611226;
    public static final String NOTIFICATION_CHANNEL_ID = "channel_001";
    public static final String NOTIFICATION_CHANNEL_NAME = "channel_001_name";

    public static final String ACTION_STATUS_UPDATE = "com.bear.story.PLAY_STATUS_UPDATE";

    boolean isPlaying = false;
    String trackTitle = "小故事  大智慧";
    int playListSize = 0;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.d("MyService--onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.d("MyService--onStartCommand");
        Context context = getApplicationContext();
        if (intent != null) {
            if (ACTION_PLAY.equals(intent.getAction())) {
                XmPlayerManager.getInstance(context).play();
            } else if (ACTION_PAUSE.equals(intent.getAction())) {
                XmPlayerManager.getInstance(context).pause();
            } else if (ACTION_NEXT.equals(intent.getAction())) {
                XmPlayerManager.getInstance(context).playNext();
            } else {
                isPlaying = intent.getBooleanExtra("isPlaying", false);
                trackTitle = intent.getStringExtra("trackTitle");
                playListSize = intent.getIntExtra("playListSize", 0);
                LogUtils.d("isPlaying=" + isPlaying + "  trackTitle=" + trackTitle + "  playListSize=" + playListSize);
            }
        }
        updateNotification(isPlaying, trackTitle, playListSize);
        return START_NOT_STICKY;
    }

    public static Intent getPlayIntent(Context context, String action) {
        Intent intent = new Intent(context, MyService.class);
        intent.putExtra("isPlaying", XmPlayerManager.getInstance(context).isPlaying());
        int index = XmPlayerManager.getInstance(context).getCurrentIndex();
        List<Track> list = XmPlayerManager.getInstance(context).getPlayList();
        //TODO: cannot get list in :player process
        if (list != null && list.size() > 0 && index < list.size()) {
            Track track = list.get(index);
            intent.putExtra("trackTitle", track.getTrackTitle());
            intent.putExtra("playListSize", list.size());
        } else {
            intent.putExtra("playListSize", 0);
        }
        intent.setAction(action);
        return intent;
    }

    private String getNowPlayBookName() {
        SharedPreferences preferences = getApplicationContext().getSharedPreferences("settings", 0);
        return preferences.getString("nowPlayBookName", "");
    }

    private void updateNotification(boolean isPlaying, String trackTitle, int playListSize) {
        Context context = getApplicationContext();
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        Notification notification = null;
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.view_notify_play);
        if (isPlaying) {
            remoteViews.setImageViewResource(R.id.img_notifyPlayOrPause, R.drawable.notify_btn_dark_pause2_normal_xml);
        } else {
            remoteViews.setImageViewResource(R.id.img_notifyPlayOrPause, R.drawable.notify_btn_dark_play2_normal_xml);
        }
        if (playListSize <= 0) {
            remoteViews.setOnClickPendingIntent(R.id.img_notifyNext, null);
            remoteViews.setOnClickPendingIntent(R.id.img_notifyPlayOrPause, null);
        } else {
            remoteViews.setOnClickPendingIntent(R.id.img_notifyNext, PendingIntent.getService(context, 0, getPlayIntent(context, ACTION_NEXT), 0));
            if (isPlaying) {
                remoteViews.setOnClickPendingIntent(R.id.img_notifyPlayOrPause, PendingIntent.getService(context, 0, getPlayIntent(context, ACTION_PAUSE), 0));
            } else {
                remoteViews.setOnClickPendingIntent(R.id.img_notifyPlayOrPause, PendingIntent.getService(context, 0, getPlayIntent(context, ACTION_PLAY), 0));
            }
            remoteViews.setTextViewText(R.id.txt_notifyMusicName, trackTitle);
            String nowPlayBookName = getNowPlayBookName();
            remoteViews.setTextViewText(R.id.txt_notifyNickName, nowPlayBookName);
        }

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(context, NOTIFICATION_CHANNEL_ID)
                    .setCustomContentView(remoteViews)
                    .setOngoing(true)//设置是否常驻,true为常驻
                    .setChannelId(NOTIFICATION_CHANNEL_ID)
                    .setContentIntent(contentIntent)
//                    .setContentTitle("活动")
//                    .setContentText("您有一项新活动")
                    .setSmallIcon(R.mipmap.ic_launcher).build();
        } else {
            notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setChannelId(NOTIFICATION_CHANNEL_ID)
                    .setCustomContentView(remoteViews)
                    .setWhen(System.currentTimeMillis())
                    .setContentIntent(contentIntent)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setOngoing(true)//设置是否常驻,true为常驻
                    .build();
        }
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
//
//        notificationManager.notify(1, notification);
        startForeground(NOTIFICATION_ID, notification);
    }

    @Override
    public void onDestroy() {
        stopForeground(true);
        super.onDestroy();
    }
}
